import React, { useEffect, useState } from 'react';
import { Card, Table, message } from 'antd';
import { getReport } from '@/services/cpasRequest';
import { request } from 'umi';
import './ReportTable.less';

interface ReportTableProps {
  bsdwxydms?: string; // 对应TreeSection选中项的xydm
  reporttype?: string; // 对应ReportTreeSection选中项的title
}

export const ReportTable: React.FC<ReportTableProps> = ({ bsdwxydms, reporttype }) => {
  const [tableData, setTableData] = useState([]);
  const [tableColumns, setTableColumns] = useState([]);
  const [loading, setLoading] = useState(false);

  // 解析JSON字符串并转换为表格数据
  // 计算叶子节点数量（参考ExcelGrid的getLeafLength方法）
  const getLeafLength = (dataItem: any[]): number => {
    let leafCount = 0;
    const leafIteration = (parentNode: any[]) => {
      for (let i = 0; i < parentNode.length; i++) {
        const leafItem = parentNode[i];
        if (leafItem.children && leafItem.children.length > 0) {
          leafIteration(leafItem.children);
        } else {
          leafCount++;
        }
      }
    };
    leafIteration(dataItem);
    return leafCount;
  };

  // 计算表头结构（参考ExcelGrid的countHeader方法）
  const countHeader = (headerData: any[]) => {
    let columnCount = 0;
    let maxLevel = 0;
    let leaf: any[] = [];
    const processedHeaderData = JSON.parse(JSON.stringify(headerData));

    // 深度遍历计算colspan和rowspan
    const countHeaderParams = (headerData: any[], level: number, parent: any = null, lastLabel: string = '') => {
      for (let i = 0; i < headerData.length; i++) {
        const dataItem = headerData[i];
        dataItem.cmap = lastLabel + dataItem.label;
        
        if (dataItem.children && dataItem.children.length > 0) {
          // 父节点
          dataItem.colspan = getLeafLength([dataItem]);
          dataItem.rowspan = 1;
          dataItem.level = level;
          dataItem.type = 'title';
          dataItem.pid = parent ? parent.value : '';
          
          const newLastLabel = lastLabel + dataItem.label + '-';
          const countLevel = level + 1;
          if (maxLevel < countLevel) {
            maxLevel = countLevel;
          }
          countHeaderParams(dataItem.children, countLevel, dataItem, newLastLabel);
        } else {
          // 叶子节点
          columnCount++;
          dataItem.level = level;
          dataItem.colspan = 1;
          dataItem.type = 'header';
          dataItem.pid = parent ? parent.value : '';
          leaf.push(dataItem);
        }
      }
    };

    countHeaderParams(processedHeaderData, 1, null, '');

    // 计算叶子节点的rowspan
    for (let i = 0; i < leaf.length; i++) {
      const leafItem = leaf[i];
      leafItem.rowspan = maxLevel - leafItem.level + 1;
    }

    return { processedHeaderData, maxLevel, leaf };
  };

  // 转换为Antd Table的列结构
  const convertToAntdColumns = (headerData: any[]): any[] => {
    const convertNode = (node: any): any => {
      const config = node.config ? JSON.parse(node.config) : {};
      
      const column: any = {
        title: node.label,
        key: node.cid || node.cmap || node.label,
        width: config.width || 120,
        align: config.type === 'numeric' ? 'right' : 'left',
      };

      if (node.children && node.children.length > 0) {
        // 父节点，有子列
        column.children = node.children.map(convertNode);
      } else {
        // 叶子节点，设置dataIndex
        column.dataIndex = node.cmap || node.cid || `col_${node.label}`;
      }

      return column;
    };

    return headerData.map(convertNode);
  };

  const parseReportData = (jsonString: string) => {
    try {
      const parsedData = JSON.parse(jsonString);
      console.log('解析的数据结构:', parsedData);
      
      // 检查数据结构
      if (!parsedData || typeof parsedData !== 'object') {
        throw new Error('数据格式不正确');
      }
      
      const { headerData, displayData, columnMaps } = parsedData;
      
      // 检查新的数据结构
      if (!Array.isArray(headerData)) {
        throw new Error('headerData字段不存在或不是数组');
      }
      
      if (!Array.isArray(displayData)) {
        throw new Error('displayData字段不存在或不是数组');
      }
      
      // 过滤掉主键和rowConfig列
      const filteredHeaderData = headerData.filter((col: any) => 
        col && col.label && col.label !== '主键' && col.label !== 'rowConfig'
      );

      // 计算表头结构
      const { processedHeaderData, leaf } = countHeader(filteredHeaderData);
      
      // 转换为Antd Table的列结构
      const columns = convertToAntdColumns(processedHeaderData);
      
      // 获取所有叶子节点的dataIndex映射
      const leafColumns = leaf.map((leafNode: any) => ({
        dataIndex: leafNode.cmap || leafNode.cid || `col_${leafNode.label}`,
        originalIndex: leafNode.originalIndex
      }));
      
      // 转换数据行 - 使用displayData，跳过第一行表头
      const rows = displayData
        .slice(1) // 跳过第一行表头
        .filter((row: any[]) => Array.isArray(row) && row.length > 1) // 过滤掉空行
        .map((row: any[], rowIndex: number) => {
          const rowData: any = { key: rowIndex };
          
          // 根据叶子节点映射数据
          leafColumns.forEach((leafCol: any, colIndex: number) => {
            let dataIndex = colIndex + 1; // 默认跳过第一列（主键）
            
            // 如果有columnMaps，使用映射关系
            if (columnMaps && columnMaps[colIndex]) {
              const mapKey = columnMaps[colIndex];
              // 在displayData的第一行中找到对应的索引
              const headerRow = displayData[0];
              dataIndex = headerRow.findIndex((header: string) => header === mapKey);
              if (dataIndex === -1) dataIndex = colIndex + 1;
            }
            
            rowData[leafCol.dataIndex] = row[dataIndex] || '';
          });
          
          return rowData;
        });
      
      console.log('处理后的列结构:', columns);
      console.log('处理后的数据:', rows);
      
      setTableColumns(columns);
      setTableData(rows);
    } catch (error) {
      console.error('解析报表数据失败:', error);
      message.error(`解析报表数据失败: ${error.message || error}`);
      setTableColumns([]);
      setTableData([]);
    }
  };

  // 调用接口获取数据
  const fetchReportData = async () => {
    if (!bsdwxydms || !reporttype) {
      setTableData([]);
      setTableColumns([]);
      return;
    }

    setLoading(true);
    try {

      const response = await getReport({ 
        bsdwxydms,
        reporttype,
      })

      
      if (response && response.data) {
        // 如果response.data是字符串，则解析它
        if (typeof response.data.reportinfo === 'string') {
          parseReportData(response.data.reportinfo);
        } else {
          // 如果已经是对象，直接使用
          parseReportData(JSON.stringify(response.data));
        }
      } else {
        setTableData([]);
        setTableColumns([]);
      }
    } catch (error) {
      console.error('获取报表数据失败:', error);
      message.error('获取报表数据失败');
      setTableData([]);
      setTableColumns([]);
    } finally {
      setLoading(false);
    }
  };

  // 当参数变化时重新获取数据
  useEffect(() => {
    fetchReportData();
  }, [bsdwxydms, reporttype]);

  return (
    <div className="report-table-container">
       <Table
          columns={tableColumns}
          dataSource={tableData}
          loading={loading}
          pagination={false}
          scroll={{ x: 'max-content', y: 'calc(100vh - 120px)' }}
          size="small"
          bordered
        />
    </div>
  );
};
